package it.uniroma3.dia.digraph.io.util;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import org.graphdrawing.graphml.xmlns.EdgeType;
import org.graphdrawing.graphml.xmlns.GraphType;
import org.graphdrawing.graphml.xmlns.NodeType;

public class Initializer {
	
	public static void init(GraphType graph){
		setNodeDegrees(graph);
	}
	

	private static void setNodeDegrees(GraphType graph) {		
		Map<String, NodeType> id2node = extractNodes(graph);
		BigInteger one = new BigInteger("1");
		BigInteger currentDeg;
		
		for (EdgeType e : graph.getEdgeCollection().getEdge()){

			// increment source outdegree
			currentDeg = id2node.get(e.getSource()).getParseOutdegree();			
			if(currentDeg==null)
				id2node.get(e.getSource()).setParseOutdegree(new BigInteger("1"));
			else
				id2node.get(e.getSource()).setParseOutdegree(currentDeg.add(one));
			
			//increment target indegree
			currentDeg = id2node.get(e.getTarget()).getParseIndegree();
			if(currentDeg==null)
				id2node.get(e.getTarget()).setParseIndegree(new BigInteger("1"));
			else
				id2node.get(e.getTarget()).setParseIndegree(currentDeg.add(one));
				
		}
		
		// set to zero the in/out degree to every other node
		for (NodeType n : id2node.values()){
			if(n.getParseIndegree()==null)
				n.setParseIndegree(new BigInteger("0"));
			
			if(n.getParseOutdegree()==null)
				n.setParseOutdegree(new BigInteger("0"));
		}
		
	}

	private static Map<String, NodeType> extractNodes(GraphType graph) {
		Map<String, NodeType> result = new HashMap<String, NodeType>();
		for (NodeType n : graph.getNodeCollection().getNode())
			result.put(n.getId(), n);
		return result;
	}

}
